<?php

namespace Connect;

/**
 * 客户端连接管理类
 * 管理workerman的连接
 */
class ConnectManager
{
    protected static $instance;

    public static function getInstance()
    {
        if (!self::$instance) {
            self::$instance = new self();
        }

        return self::$instance;
    }

    protected function __construct()
    {

    }
    /**
     *
     * @var int 当前连接数量
     */
    protected $count = 0;

    /**
     * @var array 进程数组
     */
    protected $workers = [

    ];

    /**
     *
     * @var array 客户端连接信息数组
     * [
     *   connect_id => data
     * ]
     */
    protected $clients =  [];

    /**
     * 获取当前连接数量
     *
     * @return int
     */
    public function getCount()
    {
        return $this->count;
    }

    /**
     * 增加客户端
     *
     * @return void
     */
    public function addClient($worker_id, $connect_id, $connection, $data = null)
    {
        if (!isset($this->workers[$worker_id])) {
            $this->workers[$worker_id] = [
                'clients' => [],
                'count' => 0
            ];
        }

        $this->workers[$worker_id]['clients'][$connect_id] = $connection;
        $this->workers[$worker_id]['count']++;
        $this->count++;
    }

    /**
     * 移除客户端
     *
     * @param mixed $connect_id 客户端id
     * @return void
     */
    public function removeClient($worker_id, $connect_id)
    {
        if (isset($this->workers[$worker_id]['clients'][$connect_id])) {
            unset($this->workers[$worker_id]['clients'][$connect_id]);
            $this->workers[$worker_id]['count']--;
        }
    }

    public function getClient($worker_id, $connect_id)
    {
        return isset($this->workers[$worker_id]['clients'][$connect_id]) ? $this->workers[$worker_id]['clients'][$connect_id] : null;
    }

    /**
     * 获取所有客户端
     *
     * @return array
     */
    public function getClients($worker_id)
    {
        return isset($this->workers[$worker_id]) ? $this->workers[$worker_id]['clients'] : [];
    }
}
